package com.stedu.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.stedu.bean.Account;
import com.stedu.bean.Admin;
import com.stedu.exception.SteduException;
import com.stedu.mapper.AccountMapper;
import com.stedu.mapper.AdminMapper;
import com.stedu.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    AccountMapper accountMapper;

    @Cacheable(value = "book_back", key = "'adminAll'", unless = "#result == null || #result.size() == 0")
    @Override
    public List<Admin> selectAll() {
        return adminMapper.selectAll();
    }

    @CacheEvict(value = "book_back", key = "'adminAll'")
    @Override
    public boolean insertAdmin(Admin admin) throws SteduException {

        return adminMapper.insertAdmin(admin) == 1;
    }

    @CacheEvict(value = "book_back", key = "'adminAll'")
    @Override
    public boolean deleteAdmin(Integer aid) {

        return adminMapper.deleteAdmin(aid) == 1;
    }

    @CacheEvict(value = "book_back", key = "'adminAll'")
    @Override
    public boolean updateAdmin(Admin admin) {
        return adminMapper.updateAdmin(admin) == 1;
    }

    @Override
    public List<Admin> selectByAname(String aname) {
        return adminMapper.selectByAname(aname);
    }

    @CacheEvict(value = "book_back", key = "'adminAll'")
    @Override
    public Admin selectByAid(Integer aid) {
        return adminMapper.selectByAid(aid);
    }

    @Override
    public Account login(String username, String password) throws SteduException {

        Account admin = accountMapper.selectUsername(username);

        if (!username.matches("^[a-zA-Z0-9]{1,9}$")) {
            throw new SteduException("用户名只能包含字母或数字，且长度不能超过9位");
        }

        if (admin == null){
            throw new SteduException("没有该用户");
        }

        if (!password.matches("^[0-9]{1,9}$")){
            throw new SteduException("密码只能是数字，且长度不能超过9位");
        }

        //对用户输入的密码进行加密 - 两次MD5加密
        String md5Pwd = SecureUtil.md5(SecureUtil.md5(password));
        if (! (md5Pwd.equals( admin.getPassword() ) ) ){
            throw new SteduException("密码错误，请确认后重新登录");
        }
        return admin;
    }

    @Override
    public Account selectAid(Integer aid) {
        return accountMapper.selectByAid(aid);
    }

}
